var express = require("express");
var router = express.Router();

const authMiddleWare = require("../../middleWare/auth");
const {
  getResult,
  updateList,
  getList,
  deleteList,
} = require("../../utils/sql");

let DATABASE = "yearly_plan";

router.get("/list", authMiddleWare, async function (req, res) {
  let { date, fold = 0 } = req.query;
  getList(DATABASE, ["date", "fold", "user_id"], [date, fold, req.auth]).then(
    (result) => {
      res.send({
        code: 0,
        data: result,
        message: "OK",
      });
    }
  );
});

router.post("/add", authMiddleWare, async function (req, res) {
  let { goal, plan, achievement, date } = req.body;
  let sql = `INSERT INTO ${DATABASE} (date,goal,plan,achievement,user_id) value(?,?,?,?,?)`;
  let paramsList = [date, goal, plan, achievement, req.auth];

  await getResult({
    sql,
    paramsList,
  });

  res.send({
    code: 0,
    message: "Add Successfully",
  });
});

router.put("/update", authMiddleWare, async function (req, res) {
  let { goal, plan, achievement, id } = req.body;
  await updateList(
    DATABASE,
    ["goal", "plan", "achievement"],
    [goal, plan, achievement],
    id
  );

  res.send({
    code: 0,
    message: "OK",
  });
});

router.put("/percent/update", authMiddleWare, async function (req, res) {
  let { percent, id } = req.body;
  if (
    (!percent && percent !== 0) ||
    typeof percent !== "number" ||
    percent > 100 ||
    percent < 0
  ) {
    res.send({
      code: 0,
      message: "invalid Percent",
    });
  }
  let updatePropList = ["percent", "checked"];
  let updateValueList = [percent];
  updateValueList.push(percent === 100 ? 1 : 0);
  await updateList(DATABASE, updatePropList, updateValueList, id);

  res.send({
    code: 0,
    message: "OK",
  });
});

router.put("/fold", authMiddleWare, async function (req, res) {
  let { fold, id } = req.body;
  await updateList(DATABASE, ["fold"], [fold], id);

  res.send({
    code: 0,
    message: "OK",
  });
});

router.delete("/delete", authMiddleWare, async function (req, res) {
  await deleteList(DATABASE, req.body.id).then(() => {
    res.send({
      code: 0,
      message: "delete Successfully",
    });
  });
});

module.exports = router;
